/*******************************************************************************
 * Package: com.hngtrust.iir.third.service.impl
 * Type:    ChinaTrustRegistrationServiceImpl
 * Date:    2021/10/14 10:26
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.third.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.hngtrust.framework.bind.ResponseInfo;
import com.hngtrust.framework.id.service.MyIdGenerator;
import com.hngtrust.framework.security.util.SecurityUtils;
import com.hngtrust.iir.company.entity.Company;
import com.hngtrust.iir.company.service.CompanyService;
import com.hngtrust.iir.third.contant.Contant;
import com.hngtrust.iir.third.controller.dto.BeneficiaryExportDTO;
import com.hngtrust.iir.third.controller.dto.BeneficiaryExportVO;
import com.hngtrust.iir.third.controller.dto.BeneficiaryImportVO;
import com.hngtrust.iir.third.controller.dto.BeneficiaryRequestVO;
import com.hngtrust.iir.third.controller.dto.BeneficiaryResponseVO;
import com.hngtrust.iir.third.controller.dto.BeneficiaryVO;
import com.hngtrust.iir.third.controller.dto.CtrBeneficiaryDTO;
import com.hngtrust.iir.third.controller.dto.CtrBeneficiaryExportDTO;
import com.hngtrust.iir.third.entity.CtrBeneficiary;
import com.hngtrust.iir.third.entity.CtrLog;
import com.hngtrust.iir.third.service.BeneficiaryService;
import com.hngtrust.iir.third.service.CtrBeneficiaryService;
import com.hngtrust.iir.third.service.CtrLogService;
import com.hngtrust.iir.third.util.MD5Util;
import com.hngtrust.iir.user.entity.User;
import com.tiger.excel.ExcelUtils;
import com.tiger.util.MyHttpClient;
import com.tiger.web.service.FileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 调用中信登第三方接口（受益所有人）
 *
 * @author Yujiaqi
 * @date 2021/10/14 10:26
 */
@Service
@Slf4j
public class BeneficiaryServiceImpl implements BeneficiaryService {
    
    @Value("${beneficiaryUrl.url}")
    private String beneficiaryUrl;
    
    @Value("${citicceng.url}")
    private String citicceng;
    
    @Value("${zxd.cust_no1}")
    private String custNo1;
    
    @Value("${zxd.cust_no2}")
    private String custNo2;
    
    @Value("${zxd.md5key}")
    private String md5key;
    
    @Autowired
    private MyIdGenerator myIdGenerator;
    /** 中信登接口日志表 */
    @Autowired
    private CtrLogService ctrLogService;
    /** 中信登受益人 */
    @Autowired
    private CtrBeneficiaryService ctrBeneficiaryService;
    /** 投研公司表 */
    @Autowired
    private CompanyService companyService;
    
    @Autowired
    private FileService fileService;
    
    @Autowired
    @Qualifier("localFileService")
    private FileService localFileService;
    
    /**
     * 受益所有人查询
     * @param beneficiaryVO
     */
    @Override
    public ResponseInfo<List<CtrBeneficiaryDTO>> beneficiary(BeneficiaryVO beneficiaryVO) throws JsonProcessingException {
        //签名
        String dgtSgnDscMd5 = null;
        //根据公司id或者key到中信登接口日志表查询数据，如果有则返回对应的受益人，如果没有则执行下方法
        String param;
        if(beneficiaryVO.getCompId() != null){
            param = String.valueOf(beneficiaryVO.getCompId());
        }else if(StringUtils.isNotBlank(beneficiaryVO.getKey())){
            param = beneficiaryVO.getKey();
        }else {
            return new ResponseInfo();
        }
        Long ctrLogId = ctrLogService.queryCtrLog(param,Contant.SYR_INTERFACE_TYPE);
        //判断是否为空，如果不为空，直接返回对应受益人数据，为空则调用中信登接口查询
        if(ctrLogId != null){
            CtrBeneficiary ctrBeneficiary = new CtrBeneficiary();
            ctrBeneficiary.setLogId(ctrLogId);
            List<CtrBeneficiary> ctrBeneficiaries = ctrBeneficiaryService.queryList(ctrBeneficiary);
            if(ctrBeneficiaries.size() == 0){
                CtrLog ctrLog = ctrLogService.queryById(ctrLogId);
                return new ResponseInfo(Contant.SUCCESS ,ctrLog.getFailReason());
            }
            return new ResponseInfo(ctrBeneficiaries);
        }else {
            //中信登接口日志表ID
            long ctrLogID = myIdGenerator.nextId();
            //请求流水号
            String reqNo = String.valueOf(myIdGenerator.nextId());
            //创建中信登接口日志对象
            CtrLog ctrLog = new CtrLog();
            //定义调用中信登接口的queryType参数
            String queryType;
            //判断公司id是否有值，有值则查询公司表（company），没值则确认输入值为（公司名或信用代码或组织机构代码）
            if(beneficiaryVO.getCompId() != null){
                Company company = companyService.queryById(beneficiaryVO.getCompId());
                ctrLog.setCompId(company.getId());
                ctrLog.setCompName(company.getName());
                ctrLog.setCreditCode(company.getCreditCode());
                ctrLog.setOrgCode(company.getOrgCode());
                queryType = "0";
                param = company.getName();
                // 签名规则Md5(queryType&queryContent|MD5KEY)
                String dgtSgnDsc = queryType + "&" + company.getName() + "|" + md5key;
                dgtSgnDscMd5 = MD5Util.mD5Bit32(dgtSgnDsc).toLowerCase();
            }else {
                // 判断规则确定是 信用代码/公司名称/组织机构
                String key = beneficiaryVO.getKey();
                String regex = "^[0-9A-Za-z]{18}$";
                String regex1 = "^[a-zA-Z0-9-]{9,10}$";
                //0-企业名称  1-统一社会信用代码  2-组织机构代码
                if(key.matches(regex)){
                    queryType = "1";
                    ctrLog.setCreditCode(param);
                }else if(key.matches(regex1)){
                    queryType = "2";
                    ctrLog.setOrgCode(param);
                }else {
                    queryType = "0";
                    ctrLog.setCompName(param);
                }
            }
            Date date = new Date();
            
            ctrLog.setId(ctrLogID);
            ctrLog.setInterfaceType(Contant.SYR_INTERFACE_TYPE);
            ctrLog.setReqNo(reqNo);
            ctrLog.setStatus(Contant.STATUS);
            ctrLog.setCreateTime(date);
            ctrLog.setUpdateTime(date);
            //获取当前登录人
            User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
            ctrLog.setCreateUserId(loginUser.getId());
            ctrLog.setUpdateUserId(loginUser.getId());
            ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_1);
            
            /* 调中信登收益所有人参数列表所需参数 */
            BeneficiaryRequestVO beneficiaryRequestVO = new BeneficiaryRequestVO();
            /** head添加参数 */
            BeneficiaryRequestVO.Head head = new BeneficiaryRequestVO.Head();
    
            SimpleDateFormat specificDate = new SimpleDateFormat("yyyyMMdd");
            SimpleDateFormat hourMinuteAndSecond = new SimpleDateFormat("HHmmssSSS");
            //格式化请求日期
            String specificDate1 = specificDate.format(date);
            //格式化请求时间
            String hourMinuteAndSecond1 = hourMinuteAndSecond.format(date);
            
            if (StringUtils.isNotBlank(beneficiaryVO.getKey())) {
                // 签名规则Md5(queryType&queryContent|MD5KEY)
                String dgtSgnDsc = queryType + "&" + beneficiaryVO.getKey() + "|" + md5key;
                dgtSgnDscMd5 = MD5Util.mD5Bit32(dgtSgnDsc).toLowerCase();
            }
            
            head.setTranDt(specificDate1);
            head.setTranTm(hourMinuteAndSecond1);
            head.setCharSet(Contant.CHAR_SET);
            //雪花算法生成唯一流水号
            head.setRqsSeqNo(reqNo);
            head.setSvcCd(Contant.SYR_SVC_CD);
            head.setDgtSgnDsc(dgtSgnDscMd5);
            beneficiaryRequestVO.setHead(head);
            /** body添加参数 */
            BeneficiaryRequestVO.Body body = new BeneficiaryRequestVO.Body();
            body.setCustNo1(custNo1);
            body.setCustNo2(custNo2);
            body.setQueryType(queryType);
            body.setQueryContent(param);
            beneficiaryRequestVO.setBody(body);
            //中信登接口日志表 (请求报文)
            String reqContent = JSON.toJSONString(beneficiaryRequestVO);
            ctrLog.setReqContent(reqContent);
            //中信登接口日志表新增
            ctrLogService.add(ctrLog);
            
            //调用中信登接口（受益人查询）
            String benerficiary = null;
            try {
                log.info("调用中信登受益人接口开始{}");
                MyHttpClient client = new MyHttpClient();
                benerficiary = client.postJson(beneficiaryUrl, beneficiaryRequestVO);
                log.info("中信登返回接口数据{}  "+benerficiary);
            }catch (Exception e){
                ctrLog = new CtrLog();
                ctrLog.setId(ctrLogID);
                ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
                ctrLog.setFailReason("调用中信登第三方接口(受益所有人) 调用接口异常");
                //修改中信登接口日志表 接口状态 为返回失败
                ctrLogService.modifyById(ctrLog);
                e.printStackTrace();
                log.error("调用中信登第三方接口(受益所有人) 调用接口异常{}");
                return new ResponseInfo("error","访问中信登第三方接口异常!");
            }
            BeneficiaryResponseVO beneficiaryResponseVO = JSON.parseObject(benerficiary, BeneficiaryResponseVO.class);
            BeneficiaryResponseVO.BeneficiaryBody body1 = beneficiaryResponseVO.getBody();
            if(body1 != null) {
                String data = beneficiaryResponseVO.getBody().getData();
                BeneficiaryResponseVO.BenerficiaryData benerficiaryData = null;
                if (StringUtils.isNotBlank(data)){
                    benerficiaryData = JSON.parseObject(data, BeneficiaryResponseVO.BenerficiaryData.class);
                }
                //获取中信登（受益人）结果
                BeneficiaryResponseVO.BenerficiaryData data1 = null;
                List<BeneficiaryResponseVO.BenerficiaryBene> bene = null;
                if (StringUtils.isNotBlank(data)) {
                    data1 = benerficiaryData;
                    bene = benerficiaryData.getBene();
                }
                //获取返回状态
                String retCd = beneficiaryResponseVO.getHead().getRetCd();
                if(retCd.equals(Contant.RET_CD)){
                    String resultDetailCode = beneficiaryResponseVO.getBody().getResultDetailCode();
                    if ("00".equals(resultDetailCode)) {
                        List<CtrBeneficiary> ctrBeneficiaries = new ArrayList<>();
                        if (bene != null && bene.size() > 0) {
                            for (BeneficiaryResponseVO.BenerficiaryBene benerficiaryBene : bene) {
                                CtrBeneficiary ctrBeneficiary = new CtrBeneficiary();
                                //中信登受益人ID
                                long ctrBeneficiaryId = myIdGenerator.nextId();
                                ctrBeneficiary.setId(ctrBeneficiaryId);
                                ctrBeneficiary.setLogId(ctrLogID);
                                ctrBeneficiary.setCompName(data1.getCpName());
                                ctrBeneficiary.setCreditCode(data1.getCreditCode());
                                ctrBeneficiary.setOrgCode(data1.getOrgNo());
                                ctrBeneficiary.setBeneName(benerficiaryBene.getBeneName());
                                ctrBeneficiary.setBeneType(benerficiaryBene.getBeneType());
                                ctrBeneficiary.setScore(benerficiaryBene.getScore());
                                ctrBeneficiary.setScoreDirect(benerficiaryBene.getScoreDirect());
                                ctrBeneficiary.setScoreIndirect(benerficiaryBene.getScoreIndirect());
                                ctrBeneficiary.setTitles(benerficiaryBene.getTitles());
                                ctrBeneficiary.setUpperPath(benerficiaryBene.getUpperPath());
                                ctrBeneficiary.setReason(benerficiaryBene.getReason());
                                ctrBeneficiary.setStatus(Contant.STATUS);
                                ctrBeneficiary.setCreateTime(date);
                                ctrBeneficiary.setUpdateTime(date);
                                ctrBeneficiary.setCreateUserId(loginUser.getId());
                                ctrBeneficiary.setUpdateUserId(loginUser.getId());
                                ctrBeneficiaries.add(ctrBeneficiary);
                            }
                            //批量新增受益人数据
                            ctrBeneficiaryService.addList(ctrBeneficiaries);
                        }
                        //修改中信登接口日志表接口状态等
                        ctrLog = new CtrLog();
                        ctrLog.setId(ctrLogID);
                        ctrLog.setDataCount(bene.size());
                        ctrLog.setRetContent(benerficiary);
                        ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_2);
                        if(bene == null || bene.size() == 0){
                            ctrLog.setFailReason("查询成功无数据");
                        }
                        ctrLogService.modifyById(ctrLog);
                        if(bene == null || bene.size() == 0){
                            return new ResponseInfo(Contant.SUCCESS,ctrLog.getFailReason());
                        }else {
                            //转换list，给前端返回
                            List<CtrBeneficiaryDTO> ctrBeneficiaryDTOS = JSON
                                    .parseObject(JSON.toJSONString(ctrBeneficiaries), new TypeReference<List<CtrBeneficiaryDTO>>() {
                                    });
                            return new ResponseInfo(ctrBeneficiaryDTOS);
                        }
                    }else{
                        //修改中信登接口日志表接口状态等
                        ctrLog = new CtrLog();
                        ctrLog.setId(ctrLogID);
                        if(bene == null) {
                            ctrLog.setDataCount(0);
                        }else{
                            ctrLog.setDataCount(bene.size());
                        }
                        ctrLog.setRetContent(benerficiary);
                        ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_2);
                        ctrLog.setFailReason(beneficiaryResponseVO.getBody().getResultDetailMsg());
                        ctrLogService.modifyById(ctrLog);
                        return new ResponseInfo(Contant.SUCCESS,beneficiaryResponseVO.getBody().getResultDetailMsg());
                    }
                }else {
                    //修改中信登接口日志表接口状态为失败，及失败原因
                    ctrLog = new CtrLog();
                    ctrLog.setId(ctrLogID);
                    ctrLog.setRetContent(benerficiary);
                    ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
                    ctrLog.setFailReason(beneficiaryResponseVO.getHead().getRetMsg());
                    ctrLog.setDataCount(0);
                    ctrLogService.modifyById(ctrLog);
                    return new ResponseInfo(retCd,beneficiaryResponseVO.getHead().getRetMsg());
                }
            }else {
                //修改中信登接口日志表接口状态为失败，及失败原因
                ctrLog = new CtrLog();
                ctrLog.setId(ctrLogID);
                ctrLog.setRetContent(benerficiary);
                ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
                ctrLog.setFailReason(beneficiaryResponseVO.getHead().getRetMsg());
                ctrLog.setDataCount(0);
                ctrLogService.modifyById(ctrLog);
                return new ResponseInfo(beneficiaryResponseVO.getHead().getRetCd(), beneficiaryResponseVO.getHead().getRetMsg());
            }
        }
    }
    
    /**
     * 受益人模板下载
     */
    @Override
    public void templateDownload(HttpServletResponse response) throws IOException {
        // minio上下载Excel模板文件
        fileService.download(citicceng, response);
    }
    
    /**
     * 受益人数据导出
     */
    @Override
    public void dataExport(BeneficiaryExportVO beneficiaryExport,HttpServletResponse response) throws IOException {
        String[] ids = beneficiaryExport.getId();
        if(ids != null) {
            //查询受益人所有数据
            List<CtrBeneficiary> list = ctrBeneficiaryService.queryBeneficiaryById(ids);
            List<BeneficiaryExportDTO> beneficiaryExportDTOList = new ArrayList<>();
            //序号
            int i = 1;
            if (list != null && list.size() >0){
                for (CtrBeneficiary ctrBeneficiary : list) {
                    BeneficiaryExportDTO beneficiaryExportDTO = new BeneficiaryExportDTO();
                    beneficiaryExportDTO.setSerialNumber(i++);
                    beneficiaryExportDTO.setCompName(ctrBeneficiary.getCompName());
                    beneficiaryExportDTO.setBeneName(ctrBeneficiary.getBeneName());
                    beneficiaryExportDTO.setBeneType(ctrBeneficiary.getBeneType());
                    beneficiaryExportDTO.setTitles(ctrBeneficiary.getTitles());
                    beneficiaryExportDTO.setScore(ctrBeneficiary.getScore());
                    beneficiaryExportDTO.setScoreDirect(ctrBeneficiary.getScoreDirect());
                    beneficiaryExportDTO.setScoreIndirect(ctrBeneficiary.getScoreIndirect());
                    beneficiaryExportDTO.setUpperPath(ctrBeneficiary.getUpperPath());
                    beneficiaryExportDTO.setReason(ctrBeneficiary.getReason());
                    beneficiaryExportDTO.setCreateTime(ctrBeneficiary.getCreateTime());
                    beneficiaryExportDTOList.add(beneficiaryExportDTO);
                }
            }
            String directory = System.getProperty("java.io.tmpdir");
            File file = new File(directory,"beneficiary.xls");
            //导出数据到本机默认路径
            ExcelUtils.export2Excel(beneficiaryExportDTOList,file);
            //下载文件，下载成功后删除文件
            localFileService.download(file.getAbsolutePath(), response);
            try {
                if(!file.delete()){
                    log.error("删除本地临时文件错误：{}" , directory+"/"+file.getName());
                }
            }
            catch (Exception e) {
                log.error("删除本地临时文件错误：{}" , directory+"/"+file.getName());
            }
        }
    }
    
    /**
     * 更新中信登受益人数据
     * @param beneficiaryVO
     * @return
     */
    @Override
    public ResponseInfo<List<CtrBeneficiaryDTO>> updateBeneficiary(BeneficiaryVO beneficiaryVO) {
        //签名
        String dgtSgnDscMd5 = null;
        //根据公司id或者key到中信登接口日志表查询数据，如果有则返回对应的受益人，如果没有则执行下方法
        String param;
        if(beneficiaryVO.getCompId() != null){
            param = String.valueOf(beneficiaryVO.getCompId());
        }else{
            param = beneficiaryVO.getKey();
        }
        //中信登接口日志表ID
        long ctrLogID = myIdGenerator.nextId();
        //请求流水号
        String reqNo = String.valueOf(myIdGenerator.nextId());
        //创建中信登接口日志对象
        CtrLog ctrLog = new CtrLog();
        //定义调用中信登接口的queryType参数
        String queryType;
        //判断公司id是否有值，有值则查询公司表（company），没值则确认输入值为（公司名或信用代码或组织机构代码）
        if(beneficiaryVO.getCompId() != null){
            Company company = companyService.queryById(beneficiaryVO.getCompId());
            ctrLog.setCompId(company.getId());
            ctrLog.setCompName(company.getName());
            ctrLog.setCreditCode(company.getCreditCode());
            ctrLog.setOrgCode(company.getOrgCode());
            queryType = "0";
            param = company.getName();
            // 签名规则Md5(queryType&queryContent|MD5KEY)
            String dgtSgnDsc = queryType + "&" + company.getName() + "|" + md5key;
            dgtSgnDscMd5 = MD5Util.mD5Bit32(dgtSgnDsc).toLowerCase();
        }else {
            // 判断规则确定是 信用代码/公司名称/组织机构
            String key = beneficiaryVO.getKey();
            String regex = "^[0-9A-Za-z]{18}$";
            String regex1 = "^[a-zA-Z0-9-]{9,10}$";
            //0-企业名称  1-统一社会信用代码  2-组织机构代码
            if(key.matches(regex)){
                queryType = "1";
                ctrLog.setCreditCode(param);
            }else if(key.matches(regex1)){
                queryType = "2";
                ctrLog.setOrgCode(param);
            }else {
                queryType = "0";
                ctrLog.setCompName(param);
            }
        }
        Date date = new Date();
    
        ctrLog.setId(ctrLogID);
        ctrLog.setInterfaceType(Contant.SYR_INTERFACE_TYPE);
        ctrLog.setReqNo(reqNo);
        ctrLog.setStatus(Contant.STATUS);
        ctrLog.setCreateTime(date);
        ctrLog.setUpdateTime(date);
        //获取当前登录人
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        ctrLog.setCreateUserId(loginUser.getId());
        ctrLog.setUpdateUserId(loginUser.getId());
        ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_1);
    
        /* 调中信登收益所有人参数列表所需参数 */
        BeneficiaryRequestVO beneficiaryRequestVO = new BeneficiaryRequestVO();
        /** head添加参数 */
        BeneficiaryRequestVO.Head head = new BeneficiaryRequestVO.Head();
    
        SimpleDateFormat specificDate = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat hourMinuteAndSecond = new SimpleDateFormat("HHmmssSSS");
        //格式化请求日期
        String specificDate1 = specificDate.format(date);
        //格式化请求时间
        String hourMinuteAndSecond1 = hourMinuteAndSecond.format(date);
    
        if (StringUtils.isNotBlank(beneficiaryVO.getKey())) {
            // 签名规则Md5(queryType&queryContent|MD5KEY)
            String dgtSgnDsc = queryType + "&" + beneficiaryVO.getKey() + "|" + md5key;
            dgtSgnDscMd5 = MD5Util.mD5Bit32(dgtSgnDsc).toLowerCase();
        }
    
        head.setTranDt(specificDate1);
        head.setTranTm(hourMinuteAndSecond1);
        head.setCharSet(Contant.CHAR_SET);
        //雪花算法生成唯一流水号
        head.setRqsSeqNo(reqNo);
        head.setSvcCd(Contant.SYR_SVC_CD);
        head.setDgtSgnDsc(dgtSgnDscMd5);
        beneficiaryRequestVO.setHead(head);
        /** body添加参数 */
        BeneficiaryRequestVO.Body body = new BeneficiaryRequestVO.Body();
        body.setCustNo1(custNo1);
        body.setCustNo2(custNo2);
        body.setQueryType(queryType);
        body.setQueryContent(param);
        beneficiaryRequestVO.setBody(body);
        //中信登接口日志表 (请求报文)
        String reqContent = JSON.toJSONString(beneficiaryRequestVO);
        ctrLog.setReqContent(reqContent);
        //中信登接口日志表新增
        ctrLogService.add(ctrLog);
        
        //调用中信登接口（受益人查询）
        String benerficiary = null;
        try {
            log.info("调用中信登受益人接口开始{}");
            MyHttpClient client = new MyHttpClient();
            benerficiary = client.postJson(beneficiaryUrl, beneficiaryRequestVO);
            log.info("中信登返回接口数据{}  "+benerficiary);
        }catch (Exception e){
            ctrLog = new CtrLog();
            ctrLog.setId(ctrLogID);
            ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
            ctrLog.setFailReason("调用中信登第三方接口(受益所有人) 调用接口异常");
            //修改中信登接口日志表 接口状态 为返回失败
            ctrLogService.modifyById(ctrLog);
            e.printStackTrace();
            log.error("调用中信登第三方接口(受益所有人) 调用接口异常{}");
            return new ResponseInfo("error","访问中信登第三方接口异常!");
        }
        BeneficiaryResponseVO beneficiaryResponseVO = JSON.parseObject(benerficiary, BeneficiaryResponseVO.class);
        String data = beneficiaryResponseVO.getBody().getData();
        BeneficiaryResponseVO.BenerficiaryData benerficiaryData = null;
        if (StringUtils.isNotBlank(data)){
            benerficiaryData = JSON.parseObject(data, BeneficiaryResponseVO.BenerficiaryData.class);
        }
        //获取中信登（受益人）结果
        BeneficiaryResponseVO.BenerficiaryData data1 = null;
        List<BeneficiaryResponseVO.BenerficiaryBene> bene = null;
        if (StringUtils.isNotBlank(data)) {
            data1 = benerficiaryData;
            bene = benerficiaryData.getBene();
        }
        //获取返回状态
        String retCd = beneficiaryResponseVO.getHead().getRetCd();
        if(retCd.equals(Contant.RET_CD)){
            String resultDetailCode = beneficiaryResponseVO.getBody().getResultDetailCode();
            if ("00".equals(resultDetailCode)) {
                List<CtrBeneficiary> ctrBeneficiaries = new ArrayList<>();
                if (bene != null && bene.size() > 0) {
                    for (BeneficiaryResponseVO.BenerficiaryBene benerficiaryBene : bene) {
                        CtrBeneficiary ctrBeneficiary = new CtrBeneficiary();
                        //中信登受益人ID
                        long ctrBeneficiaryId = myIdGenerator.nextId();
                        ctrBeneficiary.setId(ctrBeneficiaryId);
                        ctrBeneficiary.setLogId(ctrLogID);
                        ctrBeneficiary.setCompName(data1.getCpName());
                        ctrBeneficiary.setCreditCode(data1.getCreditCode());
                        ctrBeneficiary.setOrgCode(data1.getOrgNo());
                        ctrBeneficiary.setBeneName(benerficiaryBene.getBeneName());
                        ctrBeneficiary.setBeneType(benerficiaryBene.getBeneType());
                        ctrBeneficiary.setScore(benerficiaryBene.getScore());
                        ctrBeneficiary.setScoreDirect(benerficiaryBene.getScoreDirect());
                        ctrBeneficiary.setScoreIndirect(benerficiaryBene.getScoreIndirect());
                        ctrBeneficiary.setTitles(benerficiaryBene.getTitles());
                        ctrBeneficiary.setUpperPath(benerficiaryBene.getUpperPath());
                        ctrBeneficiary.setReason(benerficiaryBene.getReason());
                        ctrBeneficiary.setStatus(Contant.STATUS);
                        ctrBeneficiary.setCreateTime(date);
                        ctrBeneficiary.setUpdateTime(date);
                        ctrBeneficiary.setCreateUserId(loginUser.getId());
                        ctrBeneficiary.setUpdateUserId(loginUser.getId());
                        ctrBeneficiaries.add(ctrBeneficiary);
                    }
                    //批量新增受益人数据
                    ctrBeneficiaryService.addList(ctrBeneficiaries);
                }
                //修改中信登接口日志表接口状态等
                ctrLog = new CtrLog();
                ctrLog.setId(ctrLogID);
                ctrLog.setDataCount(bene.size());
                ctrLog.setRetContent(benerficiary);
                ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_2);
                if(bene == null || bene.size() == 0){
                    ctrLog.setFailReason("查询成功无数据");
                }
                ctrLogService.modifyById(ctrLog);
                if(bene == null || bene.size() == 0){
                    return new ResponseInfo(Contant.SUCCESS,ctrLog.getFailReason());
                }else {
                    //转换list，给前端返回
                    List<CtrBeneficiaryDTO> ctrBeneficiaryDTOS = JSON
                            .parseObject(JSON.toJSONString(ctrBeneficiaries), new TypeReference<List<CtrBeneficiaryDTO>>() {
                            });
                    return new ResponseInfo(ctrBeneficiaryDTOS);
                }
            }else{
                //修改中信登接口日志表接口状态等
                ctrLog = new CtrLog();
                ctrLog.setId(ctrLogID);
                if(bene == null) {
                    ctrLog.setDataCount(0);
                }else{
                    ctrLog.setDataCount(bene.size());
                }
                ctrLog.setRetContent(benerficiary);
                ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_2);
                ctrLog.setFailReason(beneficiaryResponseVO.getBody().getResultDetailMsg());
                ctrLogService.modifyById(ctrLog);
                return new ResponseInfo(Contant.SUCCESS,beneficiaryResponseVO.getBody().getResultDetailMsg());
            }
        }else {
            //修改中信登接口日志表接口状态为失败，及失败原因
            ctrLog = new CtrLog();
            ctrLog.setId(ctrLogID);
            ctrLog.setDataCount(0);
            ctrLog.setRetContent(benerficiary);
            ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
            ctrLog.setFailReason(beneficiaryResponseVO.getHead().getRetMsg());
            ctrLogService.modifyById(ctrLog);
            return new ResponseInfo(retCd,beneficiaryResponseVO.getHead().getRetMsg());
        }
    }
    
    /**
     * 批量调用中债登数据
     * @param file)
     * @return
     */
    @Override
    public ResponseInfo<List<CtrBeneficiaryExportDTO>> addBeneficiarys(MultipartFile file) throws IOException {
        final File tempFile = File.createTempFile("temp", ".xls");
        FileUtils.copyInputStreamToFile(file.getInputStream(), tempFile);
        List<BeneficiaryImportVO> beneficiaryImportVOS = null;
        beneficiaryImportVOS = ExcelUtils.importFromExcel(tempFile, BeneficiaryImportVO.class);
        if (beneficiaryImportVOS.size()>50) {
            beneficiaryImportVOS = beneficiaryImportVOS.subList(0, 50);
        }
        //获取当前登录人
        User loginUser = (User) SecurityUtils.getLoginUser().getAdditionalInfo();
        //此批次数据入库的开始时间
        Date saveDateTime = new Date();
        if(beneficiaryImportVOS != null && beneficiaryImportVOS.size() >0) {
            for (BeneficiaryImportVO beneficiaryImportVO : beneficiaryImportVOS) {
                //签名
                String dgtSgnDscMd5 = null;
                //公司名称
                String param = beneficiaryImportVO.getCompName();
                //中信登接口日志表ID
                long ctrLogID = myIdGenerator.nextId();
                //请求流水号
                String reqNo = String.valueOf(myIdGenerator.nextId());
                //创建中信登接口日志对象
                CtrLog ctrLog = new CtrLog();
                //定义调用中信登接口的queryType参数
                String queryType = "0";
                ctrLog.setCompName(beneficiaryImportVO.getCompName());
                if (StringUtils.isNotBlank(beneficiaryImportVO.getCreditCode())) {
                    ctrLog.setCreditCode(beneficiaryImportVO.getCreditCode());
                }
                if (StringUtils.isNotBlank(beneficiaryImportVO.getOrgCode())) {
                    ctrLog.setOrgCode(beneficiaryImportVO.getOrgCode());
                }
        
                Date date = new Date();
        
                ctrLog.setId(ctrLogID);
                ctrLog.setInterfaceType(Contant.SYR_INTERFACE_TYPE);
                ctrLog.setReqNo(reqNo);
                ctrLog.setStatus(Contant.STATUS);
                ctrLog.setCreateTime(date);
                ctrLog.setUpdateTime(date);
                ctrLog.setCreateUserId(loginUser.getId());
                ctrLog.setUpdateUserId(loginUser.getId());
                ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_1);
        
                /* 调中信登收益所有人参数列表所需参数 */
                BeneficiaryRequestVO beneficiaryRequestVO = new BeneficiaryRequestVO();
                /** head添加参数 */
                BeneficiaryRequestVO.Head head = new BeneficiaryRequestVO.Head();
        
                SimpleDateFormat specificDate = new SimpleDateFormat("yyyyMMdd");
                SimpleDateFormat hourMinuteAndSecond = new SimpleDateFormat("HHmmssSSS");
                //格式化请求日期
                String specificDate1 = specificDate.format(date);
                //格式化请求时间
                String hourMinuteAndSecond1 = hourMinuteAndSecond.format(date);
        
                // 签名规则Md5(queryType&queryContent|MD5KEY)
                String dgtSgnDsc = queryType + "&" + beneficiaryImportVO.getCompName() + "|" + md5key;
                dgtSgnDscMd5 = MD5Util.mD5Bit32(dgtSgnDsc).toLowerCase();
        
                head.setTranDt(specificDate1);
                head.setTranTm(hourMinuteAndSecond1);
                head.setCharSet(Contant.CHAR_SET);
                //雪花算法生成唯一流水号
                head.setRqsSeqNo(reqNo);
                head.setSvcCd(Contant.SYR_SVC_CD);
                head.setDgtSgnDsc(dgtSgnDscMd5);
                beneficiaryRequestVO.setHead(head);
                /** body添加参数 */
                BeneficiaryRequestVO.Body body = new BeneficiaryRequestVO.Body();
                body.setCustNo1(custNo1);
                body.setCustNo2(custNo2);
                body.setQueryType(queryType);
                body.setQueryContent(param);
                beneficiaryRequestVO.setBody(body);
                //中信登接口日志表 (请求报文)
                String reqContent = JSON.toJSONString(beneficiaryRequestVO);
                ctrLog.setReqContent(reqContent);
                //中信登接口日志表新增
                ctrLogService.add(ctrLog);
        
                //调用中信登接口（受益人查询）
                String benerficiary = null;
                try {
                    log.info("调用中信登受益人接口开始{}");
                    MyHttpClient client = new MyHttpClient();
                    benerficiary = client.postJson(beneficiaryUrl, beneficiaryRequestVO);
                    log.info("中信登返回接口数据{}  " + benerficiary);
                } catch (Exception e) {
                    ctrLog = new CtrLog();
                    ctrLog.setId(ctrLogID);
                    ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
                    ctrLog.setFailReason("调用中信登第三方接口(受益所有人) 调用接口异常");
                    //修改中信登接口日志表 接口状态 为返回失败
                    ctrLogService.modifyById(ctrLog);
                    e.printStackTrace();
                    log.error("调用中信登第三方接口(受益所有人) 调用接口异常{}");
                    continue;
                }
                BeneficiaryResponseVO beneficiaryResponseVO = JSON.parseObject(benerficiary, BeneficiaryResponseVO.class);
                String data = beneficiaryResponseVO.getBody().getData();
                BeneficiaryResponseVO.BenerficiaryData benerficiaryData = null;
                if (StringUtils.isNotBlank(data)) {
                    benerficiaryData = JSON.parseObject(data, BeneficiaryResponseVO.BenerficiaryData.class);
                }
                //获取中信登（受益人）结果
                BeneficiaryResponseVO.BenerficiaryData data1 = null;
                List<BeneficiaryResponseVO.BenerficiaryBene> bene = null;
                if (StringUtils.isNotBlank(data)) {
                    data1 = benerficiaryData;
                    bene = benerficiaryData.getBene();
                }
                //获取返回状态
                String retCd = beneficiaryResponseVO.getHead().getRetCd();
                if (retCd.equals(Contant.RET_CD)) {
                    String resultDetailCode = beneficiaryResponseVO.getBody().getResultDetailCode();
                    if ("00".equals(resultDetailCode)) {
                        List<CtrBeneficiary> ctrBeneficiaries = new ArrayList<>();
                        if (bene != null && bene.size() > 0) {
                            for (BeneficiaryResponseVO.BenerficiaryBene benerficiaryBene : bene) {
                                CtrBeneficiary ctrBeneficiary = new CtrBeneficiary();
                                //中信登受益人ID
                                long ctrBeneficiaryId = myIdGenerator.nextId();
                                ctrBeneficiary.setId(ctrBeneficiaryId);
                                ctrBeneficiary.setLogId(ctrLogID);
                                ctrBeneficiary.setCompName(data1.getCpName());
                                ctrBeneficiary.setCreditCode(data1.getCreditCode());
                                ctrBeneficiary.setOrgCode(data1.getOrgNo());
                                ctrBeneficiary.setBeneName(benerficiaryBene.getBeneName());
                                ctrBeneficiary.setBeneType(benerficiaryBene.getBeneType());
                                ctrBeneficiary.setScore(benerficiaryBene.getScore());
                                ctrBeneficiary.setScoreDirect(benerficiaryBene.getScoreDirect());
                                ctrBeneficiary.setScoreIndirect(benerficiaryBene.getScoreIndirect());
                                ctrBeneficiary.setTitles(benerficiaryBene.getTitles());
                                ctrBeneficiary.setUpperPath(benerficiaryBene.getUpperPath());
                                ctrBeneficiary.setReason(benerficiaryBene.getReason());
                                ctrBeneficiary.setStatus(Contant.STATUS);
                                ctrBeneficiary.setCreateTime(date);
                                ctrBeneficiary.setUpdateTime(date);
                                ctrBeneficiary.setCreateUserId(loginUser.getId());
                                ctrBeneficiary.setUpdateUserId(loginUser.getId());
                                ctrBeneficiaries.add(ctrBeneficiary);
                            }
                            //批量新增受益人数据
                            ctrBeneficiaryService.addList(ctrBeneficiaries);
                        }
                        //修改中信登接口日志表接口状态等
                        ctrLog = new CtrLog();
                        ctrLog.setId(ctrLogID);
                        ctrLog.setDataCount(bene.size());
                        ctrLog.setRetContent(benerficiary);
                        ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_2);
                        if (bene == null || bene.size() == 0) {
                            ctrLog.setFailReason("查询成功无数据");
                        }
                        ctrLogService.modifyById(ctrLog);
                        if (bene == null || bene.size() == 0) {
                            continue;
                        } else {
                            //转换list，给前端返回
                            List<CtrBeneficiaryDTO> ctrBeneficiaryDTOS = JSON
                                    .parseObject(JSON.toJSONString(ctrBeneficiaries), new TypeReference<List<CtrBeneficiaryDTO>>() {
                                    });
                            continue;
                        }
                    } else {
                        //修改中信登接口日志表接口状态等
                        ctrLog = new CtrLog();
                        ctrLog.setId(ctrLogID);
                        if(bene == null) {
                            ctrLog.setDataCount(0);
                        }else{
                            ctrLog.setDataCount(bene.size());
                        }
                        ctrLog.setRetContent(benerficiary);
                        ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_2);
                        ctrLog.setFailReason(beneficiaryResponseVO.getBody().getResultDetailMsg());
                        ctrLogService.modifyById(ctrLog);
                        continue;
                    }
                } else {
                    //修改中信登接口日志表接口状态为失败，及失败原因
                    ctrLog = new CtrLog();
                    ctrLog.setId(ctrLogID);
                    ctrLog.setDataCount(0);
                    ctrLog.setRetContent(benerficiary);
                    ctrLog.setInterfaceStatus(Contant.INTERFACE_STATUS_3);
                    ctrLog.setFailReason(beneficiaryResponseVO.getHead().getRetMsg());
                    ctrLogService.modifyById(ctrLog);
                    continue;
                }
            }
        }
        List<CtrBeneficiaryExportDTO> ctrBeneficiaryExportDTOS = new ArrayList<>();
        
        //查询ctr_log表数据,根据当前登录人，时间
        List<CtrLog> list = ctrLogService.queryBeneficiaryByNames(loginUser.getId(),saveDateTime);
        if (list != null && list.size() > 0){
            for (CtrLog ctrLog : list) {
                CtrBeneficiaryExportDTO ctrBeneficiaryExportDTO = new CtrBeneficiaryExportDTO();
                if(ctrLog.getInterfaceStatus() == 2){
                    ctrBeneficiaryExportDTO.setInterfaceResult(Contant.SYF_SUCCESS);
                }else {
                    ctrBeneficiaryExportDTO.setInterfaceResult(Contant.SYF_FAIL);
                }
                ctrBeneficiaryExportDTO.setCompName(ctrLog.getCompName());
                ctrBeneficiaryExportDTO.setFailReason(ctrLog.getFailReason());
                ctrBeneficiaryExportDTO.setBeneficiaryNum(ctrLog.getDataCount());
                ctrBeneficiaryExportDTO.setUpdateTime(ctrLog.getUpdateTime());
    
                ctrBeneficiaryExportDTOS.add(ctrBeneficiaryExportDTO);
            }
        }
        return new ResponseInfo(ctrBeneficiaryExportDTOS);
    }
    
}
